package com.springboot.codeminestarter.codemine.aop.db;

import com.springboot.codeminestarter.codemine.utils.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据库切面
 *
 * 1.扫描service包下方法注解@SwitchDB
 * 2.获取注解配置信息
 * 3.根据注解value，获取配置文件中数据库信息
 * 4.注册数据源
 *    1.将读取到的数据源注册为DataSource Bean
 */
@Aspect
@Component
@Order(-1)
public class DataSourceWrapper {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceWrapper.class);

    @Pointcut(value = "@annotation(SwitchDB)")
    private void dataSourcePointCut() {

    }

    @Before(value = "dataSourcePointCut()")
    public void methodBefore(JoinPoint point) {

        handle(point);
    }

    private String handle(JoinPoint point) {

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        // annotation value
        SwitchDB annotation = method.getAnnotation(SwitchDB.class);
        String dbType = annotation.value();
        if (StringUtil.isEmpty(dbType) || "master".equals(dbType)) {
            LOGGER.info("SwitchDB annotation value is default [{}]", dbType);
        } else {
            LOGGER.info("SwitchDB annotation value is [{}]", dbType);
            DataSourceContext.changeDBType(dbType);
        }
        return dbType;
    }

    @After(value = "dataSourcePointCut()")
    public void methodAfter(JoinPoint point) {

        LOGGER.info("销毁数据源：[{}]", DataSourceContext.getDBType());
        DataSourceContext.removeDBType();
    }
}
